package com.easy.mq.event;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.MethodInvoker;

import com.easy.mq.config.consumer.AbstractConsumerConfig;
import com.easy.mq.entry.JsonUtil;
import com.easy.mq.enums.ConsumeResultStatus;
import com.easy.mq.listener.ManagerListener;

public class ObjectListenerMethodInvokeWrapper<T> extends MethodInvoker {

	static private final Logger logger = LoggerFactory.getLogger(ObjectListenerMethodInvokeWrapper.class);

	String listenerClassName;
	String key;
	ManagerListener<T> managerListener;
	
	AbstractConsumerConfig consumerConfig;

	public void init() {
			managerListener.addMQListener(key, new MQConsumerListener() {

				@Override
				public ConsumeResultStatus onMQEvent(MQEvent<Object> event) {
					try {
						setArguments(new Object[] { event });
						if (!isPrepared()) {
							prepare();
						}
						Object obj = invoke();
						if (obj != null && obj instanceof ConsumeResultStatus) {
							return (ConsumeResultStatus) obj;
						}
					} catch (Exception e) {
						logger.error("Consumer message error:{},class:{},method:{},value:{}!" , e.getMessage(),getTargetObject(),getTargetMethod(),JsonUtil.bean2Json(event));
						return ConsumeResultStatus.FAIL;

					}
					return ConsumeResultStatus.SUCCESS;
				}

				@Override
				public ConsumeResultStatus onMQEvent(List<MQEvent<Object>> event) {
					try {
						setArguments(new Object[] { event });
						if (!isPrepared()) {
							prepare();
						}
						Object obj = invoke();
						if (obj != null && obj instanceof ConsumeResultStatus) {
							return (ConsumeResultStatus) obj;
						}
					} catch (Exception e) {
						logger.error("Consumer message error,class:{},method:{},value:{}!" , e,listenerClassName,getTargetMethod(),JsonUtil.bean2Json(event));
						return ConsumeResultStatus.FAIL;

					}
					return ConsumeResultStatus.SUCCESS;
				}
			});

			if (logger.isDebugEnabled()) {
				logger.debug("begin Listener, consumer [{}],");
			}
	}

	public ManagerListener<T> getManagerConfig() {
		return managerListener;
	}

	public void setManagerListener(ManagerListener<T> managerConfig) {
		this.managerListener = managerConfig;
	}

	public String getListenerClassName() {
		return listenerClassName;
	}

	public void setListenerClassName(String listenerClassName) {
		this.listenerClassName = listenerClassName;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public void setConsumerConfig(AbstractConsumerConfig consumerConfig) {
		this.consumerConfig = consumerConfig;
	}
	

}
